package org.noka.socketserver;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * socket服务器
 * @author rebin
 */
public class NSocketServerUtil extends Thread{
	
	private ServerSocket server = null;//socket服务
	private Integer port=null;//服务端口
	private Integer cmax=100;//客户端数量
	private ExecutorService pools=null;//线程池
	private Boolean ServerStatce=false;//服务状态
	private ClientInterface NClient=null;//操作实例
	private Integer disTime=5;//默认为5分钟
	//--------------构建方法-------------------------------------------------------------------
	public NSocketServerUtil(Integer port,ClientInterface NClient){
		NSocketServerInit(port,new Integer(200),NClient,new Integer(5));
	}
	public NSocketServerUtil(Integer port,Integer cmax,ClientInterface NClient){
		NSocketServerInit(port,cmax,NClient,new Integer(5));
	}
	
	public NSocketServerUtil(Integer port,Integer cmax,ClientInterface NClient,Integer disTime){
		NSocketServerInit(port,cmax,NClient,disTime);
	}
	
	public void NSocketServerInit(Integer port,Integer cmax,ClientInterface NClient,Integer disTime){
		this.port = port;
		this.cmax=cmax;
		this.NClient = NClient;
		this.disTime = disTime;
	}
	//--------------服务实体-------------------------------------------------------------------
	public void run(){
		try{
			server = new ServerSocket(port);
			pools = Executors.newFixedThreadPool(cmax);
			ServerStatce=true;
			while(ServerStatce){
				try {//启动服务
					Socket s = server.accept();
					s.setKeepAlive(true);//保持活动连接
					Boolean b=NClient.onConnection(s);//调用连接处理方法
					if(b){
						ClientUtil cs= new ClientUtil(s,NClient,disTime);//启动服务线程
						pools.execute(cs);
					}else{
						s.close();//断开
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}catch(Exception e){
			
		}
		ServerStatce=false;
	}
	//-----------关闭所有线程------------------------
	public void stopServer(){
		if(pools!=null){
			pools.shutdown();
		}
		ServerStatce=false;
	}
	//-----------服务状态-----------------------------
	public Boolean getServerStatce(){
		return ServerStatce;
	}

	public Integer getPort() {
		return port;
	}

	public void setPort(Integer port) {
		this.port = port;
	}

	public Integer getCmax() {
		return cmax;
	}

	public void setCmax(Integer cmax) {
		this.cmax = cmax;
	}

	public ClientInterface getNClient() {
		return NClient;
	}

	public void setNClient(ClientInterface nClient) {
		NClient = nClient;
	}

	public Integer getDisTime() {
		return disTime;
	}

	public void setDisTime(Integer disTime) {
		this.disTime = disTime;
	}
}
